package com.jd.system.service.impl;

import com.jd.org.domain.Department;
import com.jd.system.domain.Menu;
import com.jd.system.mapper.MenuMapper;
import com.jd.system.service.IMenuService;
import com.jd.basic.service.impl.BaseServiceImpl;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jd
 * @since 2023-03-09
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> first() {
        return super.findAll().stream().filter(menu -> Objects.nonNull(menu) && null == menu.getParentId()).collect(Collectors.toList());
    }

    @Override
    public List<Menu> tree() {
        // 查询所有的菜单
        List<Menu> menuAll = menuMapper.findAll();
        // 创建一个空的集合，负责状结果
        ArrayList<Menu> menus = new ArrayList<>();
        Map<Long, Menu> menuMap = menuAll.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        // 先遍历集合，找到父类
        for (Menu menu:menuAll) {
            if (menu.getParentId() == null){
                menus.add(menu);
            }else {
                Menu menuParent = menuMap.get(menu.getParentId());
                if (menuParent != null){
                    menuParent.getChildren().add(menu);
                }
            }
            System.out.println(menus);
        }
        
        return menus;
    }
}
